﻿using DJY.Code.Helper;
using System;
using System.Configuration;
using System.IO;
using System.Web;

namespace DJY.Code
{
    public static class ConfigHelper
    {
        private const string WebConfigPath = "~/web.config";

        private const string SysConfigPath = "~/Configs/system.config";

        #region 系统配置项
       
        /// <summary>
        /// 软件服务商
        /// </summary>
        public static string Vendor
        {
            get
            {
                return GetValue("Vendor");
            }
        }
        /// <summary>
        /// 系统名称
        /// </summary>
        public static string SoftName {
            get
            {
                return GetValue("SoftName");
            }
        }

        /// <summary>
        /// 版本
        /// </summary>
        public static string Version
        {
            get
            {
                return GetValue("Version");
            }
        }
        #endregion

        /// <summary>
        /// 根据Key取Value值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="defaultValue">默认值</param>
        public static string GetValue(string key, string defaultValue = null)
        {
            string result = ConfigurationManager.AppSettings[key];
            if (result == null)
            {
                result = defaultValue;
            }
            return result;
        }

        /// <summary>
        /// 根据Key修改Value
        /// </summary>
        /// <param name="key">要修改的Key</param>
        /// <param name="value">要修改为的值</param>
        /// <param name="restart">是否重启</param>
        public static void SetValue(string key, string value,bool restart = false)
        {
            string configFileName = FileHelper.MapPath(SysConfigPath);
            if (!File.Exists(configFileName))
            {
                return;
            }

            System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
            xDoc.Load(configFileName);
            System.Xml.XmlNode xNode;
            System.Xml.XmlElement xElem;
            xNode = xDoc.SelectSingleNode("//appSettings");
            xElem = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
            if (xElem == null)
            {
                xElem = xDoc.CreateElement("add");
                xElem.SetAttribute("key", key);
                xNode.AppendChild(xElem);
            }

            xElem.SetAttribute("value", value);
            xDoc.Save(configFileName);

            if(restart)
            {
                try
                {
                    File.SetLastWriteTimeUtc(FileHelper.MapPath(WebConfigPath), DateTime.UtcNow);
                }
                catch
                {
                    //do nothing
                }
            }
        }
    }
}
